import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

const service = axios.create({
  // headers: { 'Content-Type': 'application/json' },
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 0
  //, // request timeout
  // transformRequest: [function(data) {
  //   data = Qs.stringify(data)
  //   return data
  // }],
  // headers: {
  //   'Content-Type': 'application/x-www-form-urlencoded'
  // }
})

// request interceptor
service.interceptors.request.use(
  (config:any) => {
    // do something before request is sent
    // if (store.getters.token) {
    //   config.headers['Authorization'] = getToken()
    // }
    if (/get/i.test(config.method)) { // 判断get请求
      config.params = config.params || {}
      config.params.__timespan___ = new Date().valueOf() // 添加时间戳
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code === '000000') {
      return res
    } else if (res.code === -1) {
      // Message({
      //   message: res.message || res.msg || 'error',
      //   type: 'warning',
      //   duration: 5 * 1000
      // })
    } else if (res.code === 0) {
      // to re-login
      // MessageBox.confirm('您的登录已过期，请重新登录。', '登录超时', {
      //   confirmButtonText: '重新登录',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   store.dispatch('user/resetToken').then(() => {
      //     location.reload()
      //   })
      // })
    } else {
      // Message({
      //   message: res.message || res.msg || 'error',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      console.log(res)
    }
    return Promise.reject(res.message || res.msg || 'error')
  },
  error => {
    console.log('err' + error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default service
